package com.flyou.ren.gateway.config;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author fzl
 * @version 1.0.0
 * @ClassName MyGlobelGatewayFilterFactory.java
 * @Description 全局过滤器，只需要注册给spring框架就会自动执行
 * 通常用作权限过滤，全局拦截等
 * @createTime 2022/2/15 13:58
 */
@Component
public class MyGlobelGatewayFilterFactory implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("-----------------全局过滤器MyGlobalFilter---------------------");
        String token = exchange.getRequest().getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    //        可以同时定义多个全局过滤器，值越小越先执行
    @Override
    public int getOrder() {//值越小越先执行
        return 1;
    }
}

